<template>
  <div>
    <TopFilter
      ref="topFilter"
      :list="topFilterList"
      :cols="4"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :isSelectColumn="false"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
      </template>
    </FilterTable>

    <Drawer
      :visible.sync="visible"
      :title="dialogTitle"
      :width="1100"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ManualCareTaskPanel :type="handleType" :recordVersion="recordVersion" :carePlanId="carePlanId" @changeHandle="changeHandle" @close="closeHandler" />
    </Drawer>
  </div>
</template>
<script>
import {
  getCareTaskList,
  releaseManualCarePlan,
  disabledManualCarePlan,
  deleteManualCarePlan
} from '@/api/customerCare/visitRules/manualCareTask';
import {
  getUserInfoByRole,
  getUserInfo
} from '@/api/customerCare/saleVisit/careTaskSearch';
import { dictionary } from '@/utils/dictMixin';
import ManualCareTaskPanel from './manualCareTaskPanel';

export default {
  name: 'CareTask',
  mixins: [dictionary],
  components: {
    ManualCareTaskPanel
  },
  data(){
    this.conf = { add: '新增', edit: '编辑',show: '明细'};
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getCareTaskList,
      fetchParams: {},
      recordVersion: '',
      handleType: '',
      carePlanId: '',
      dialogTitle: '',
      visible: false
    }
  },
  methods: {
    createTopFilters(){
      return [
        {
          type: 'SELECT',
          label: '关爱类型',
          fieldName: 'careTypeCode',
          placeholder: '请选择...',
          itemList: [{text:"活动邀约",value:15721006}]
        },
        {
          type: 'INPUT',
          label: '关爱名称',
          fieldName: 'careName',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '分配人员',
          fieldName: 'distributeId',
          placeholder: '请输入...',
          itemList: this.createdEmpList()
        },
        {
          type: 'RANGE_DATE',
          label: '创建日期',
          fieldName: 'createdAtStart|createdAtEnd',
          format: "yyyy-MM-dd",
          placeholder: '创建日期'
        }
      ]
    },
    createTableColumns(){
      return [
       {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          width: 220,
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={props.row.releaseTag == 10651002} onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={props.row.releaseTag == 10651002} onClick={() => this.releaseHandle(props.row)}>
                  发布
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={!(props.row.releaseTag == 10651002 && props.row.whetherEnable == 10041001)} onClick={() => this.stopHandle(props.row)}>
                  停用
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={props.row.releaseTag == 10651002} onClick={() => this.deleteHandle(props.row)}>
                  删除
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '计划编号',
          dataIndex: 'planNo',
          width: 125,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '关爱类型',
          dataIndex: 'careTypeCode',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.careTypeCode, '1572')}</div>;
          }
        },
        {
          title: '关爱名称',
          dataIndex: 'careName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '模板类型',
          dataIndex: 'careWay',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.careWay, '1587')}</div>;
          }
        },
        {
          title: '创建日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '要求完成日期',
          dataIndex: 'requiredDate',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '模板名称',
          dataIndex: 'templateName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '分配人员',
          dataIndex: 'distributeUserName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发布状态',
          dataIndex: 'releaseTag',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <div>{this.createDictText(props.row.releaseTag, '1065')}</div>;
          }
        }
      ]
    },
    createdEmpList(){
      //初始化关爱人员选择列表
      getUserInfo().then(res => {
        if(res.resultCode == 200){
          let param = {
            companyId:res.data.userInfo.companyId,
            positionCode:10061015
          };
          getUserInfoByRole(param).then(res => {
            if(res.resultCode == 200){
              this.topFilterList[2].itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }))
            }else{
              this.$message.error('获取关爱人员列表失败!');
            }
          })
        }else{
          this.$message.error('获取当前登录用户信息失败!');
        }
      })
    },
    stopHandle(row){
      this.$confirm('此操作将停用这个关爱计划, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {"carePlanId":row.carePlanId,"recordVersion":row.recordVersion};
        disabledManualCarePlan(data).then(res=>{
          if(res.resultCode === 200){
            this.$message.success('停用成功!');
            this.fetchParams = { ...this.fetchParams };
          }else{
            this.$message({
              type: 'error',
              message: res.data.errMsg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}关爱计划`;
      this.visible = true;
    },
    editHandle(row){
      this.handleType = 'edit';
      this.recordVersion = row.recordVersion+'';
      this.carePlanId = row.carePlanId+'';
      this.showHandler();
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    releaseHandle(row){
      this.$confirm('此操作将发布这个关爱计划, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {"carePlanId":row.carePlanId,"recordVersion":row.recordVersion};
        releaseManualCarePlan(data).then(res=>{
          if(res.resultCode === 200){
            this.$message.success('发布成功!');
            this.fetchParams = { ...this.fetchParams };
          }else{
            this.$message({
              type: 'error',
              message: res.data.errMsg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    deleteHandle(row){
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {"carePlanId":row.carePlanId,"recordVersion":row.recordVersion};
        deleteManualCarePlan(data).then(res=>{
          if(res.resultCode === 200){
            this.$message.success('删除成功!');
            this.fetchParams = { ...this.fetchParams };
          }else{
            this.$message({
              type: 'error',
              message: res.data.errMsg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    detailHandle(row){
      this.handleType = 'show';
      this.carePlanId = row.carePlanId+'';
      this.showHandler();
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  }
}
</script>

<style lang="less">
</style>
